#coding:utf-8
import pipe
import threading
import os
from configobj import ConfigObj

@pipe.Pipe
def getTags(element,name,xmlns=None):
	if xmlns is None:
		filtAlg = lambda el : not isinstance(el,basestring) and el.name == name
	else:
		filtAlg = lambda el : not isinstance(el,basestring) and el.name == name and el.uri == xmlns
	result = filter(filtAlg,element.elements())
	return (result if result else None)
@pipe.Pipe
def getTag(element,name,xmlns = None):
	for el in element.elements():
		if not isinstance(el,basestring) and el.name == name:
			if xmlns and el.uri == xmlns:
				return el
			return el
	return None
@pipe.Pipe
def getStatusPayload(element):
	statusTag = element | getTag("status")
	if statusTag:
		return statusTag.getAttribute("code"),statusTag.__str__()
	return None,None

@pipe.Pipe
def __str__(_str):
	if hasattr(_str,"__str__"):
		return _str.__str__()
	return str(_str)

@pipe.Pipe
def strip(_str):
	return _str.strip()
	
@pipe.Pipe
def splitMessageQuery(body):
        rawbody = body.split(" ",1)
        command = rawbody[0].lower()
        param =  len(rawbody)==2 and rawbody[1] or None
        return command,param

smph = threading.Lock()

def writeFile(path, data, mode="w"):
	with smph:
		if not os.path.supports_unicode_filenames:
			path = path.encode("utf-8")
		f = file(path, mode)
		f.write(data if isinstance(data,basestring) else data | __str__)
		f.close()

def readFile(path, default=None, encoding=None):
	if not os.path.supports_unicode_filenames:
		path = path.encode("utf-8")
	if os.path.exists(path):
		f = file(path)
		data = f.read()
		f.close()
		if encoding:
			data = data.decode(encoding)
		return data
	else:
		dirname = os.path.dirname(path)
		if not os.path.exists(dirname):
			os.makedirs(dirname)
		writeFile(path, default)
		return default
		
def loadConfig(path,template = {}):
        rewrite = False
        _dir = os.path.dirname(path)
        if not os.path.isdir(_dir):
                os.makedirs(_dir)
        try:
                conf = ConfigObj(path,encoding="UTF-8")
        except ConfigObjError,e:
                 conf = e.config
                 rewrite = True
        for k,v in template.iteritems():
                if not conf.has_key(k):
                        conf[k] = v
                        rewrite = True
        if rewrite:
                conf.write()
        return conf